import { observable, action, computed, runInAction } from 'mobx';
import Cookies from 'js-cookie';

import BaseStore from '../BaseStore';
import validationUtil from '@/utils/validation';
import { noticeMessage } from '@utils/common-message';

class LoginStore extends BaseStore {
    @observable captcha;
    @observable captcha1;
    @observable captchaUrl;
    @observable captchaUrl1;
    @observable username;
    @observable username1;
    @observable password;
    @observable password1;
    @observable repeatPassword;
    @observable smsCode;
    @observable isRetrievePwdModalOpen = false;
    @observable isCaptchaModalOpen = false;
    @observable smsCodeTimeout = 0;
    @observable errMsg = {
        username: '',
        username1: '',
        password: '',
        password1: '',
        repeatPassword: '',
        captcha: '',
        captcha1: '',
        smsCode: '',
    };
    isLogon = false;
    isSendSmsCodeSuccess = false;
    isRetrievePwdSuccess = false;
    // 弹框提示的错误
    globalErrMsg = '';

    @computed
    get isLoginSubmitBtnDisabled() {
        return !this.username ||
            !this.password ||
            !this.captcha ||
            !validationUtil.isCaptcha(this.captcha);
    }

    @computed
    get isSmsCodeBtnDisabled() {
        return !this.username1 ||
            this.smsCodeTimeout > 0;
    }

    @computed
    get isSendSmsCodeBtnDisabled() {
        return !this.captcha1 || !validationUtil.isCaptcha(this.captcha1);
    }

    @computed
    get isRetrievePwdSubmitBtnDisabled() {
        return !this.username1 ||
            !this.password1 ||
            !this.repeatPassword ||
            !this.smsCode ||
            !validationUtil.isSMSCode(this.smsCode);
    }

    @action
    reset() {
        this.username = '';
        this.password = '';
        this.captcha = '';
        this.captchaUrl = '';
        this.isLogon = false;
        this.errMsg.username = '';
        this.errMsg.password = '';
        this.errMsg.repeatPassword = '';
        this.errMsg.captcha = '';
        this.resetRetrievePwd();
    }

    @action
    resetRetrievePwd() {
        this.username1 = '';
        this.password1 = '';
        this.repeatPassword = '';
        this.captcha1 = '';
        this.captchaUrl1 = '';
        this.isSendSmsCodeSuccess = false;
        this.isRetrievePwdSuccess = false;
        this.errMsg.username1 = '';
        this.errMsg.password1 = '';
        this.errMsg.repeatPassword = '';
        this.errMsg.captcha1 = '';
        this.errMsg.smsCode = '';
    }

    /**
     * 刷新图形验证码
     */
    @action
    refreshCaptcha() {
        this.captcha = '';
        this.captchaUrl = `/captcha?${Date.now()}`;
    }
    @action
    refreshCaptcha1() {
        this.captcha1 = '';
        this.captchaUrl1 = `/captcha?type=3&${Date.now()}`;
    }

    /**
     * 打开找回密码弹框
     */
    @action
    openRetrievePwdModal() {
        this.isRetrievePwdSuccess = false;
        this.isRetrievePwdModalOpen = true;
    }

    /**
     * 关闭找回密码弹框
     */
    @action
    closeRetrievePwdModal() {
        this.isRetrievePwdModalOpen = false;
    }

    /**
     * 打开图形验证码弹框
     */
    @action
    openCaptchaModal() {
        if (!this.validateUsername1()) {
            return;
        }
        this.errMsg.captcha1 = '';
        this.refreshCaptcha1();
        this.isCaptchaModalOpen = true;
    }

    /**
     * 关闭图形验证码弹框
     */
    @action
    closeCaptchaModal() {
        this.isCaptchaModalOpen = false;
    }

    /**
     * 验证用户名
     */
    @action
    validateUsername() {
        this.errMsg.username = '';
        if (!this.username) {
            this.errMsg.username = noticeMessage.inputEmpty('用户名');
            return false;
        }
        return true;
    }

    @action
    validateUsername1() {
        this.errMsg.username1 = '';
        if (!validationUtil.isMobile(this.username1)) {
            this.errMsg.username1 = noticeMessage.inputFormatError('手机号码');
            return false;
        }
        return true;
    }

    /**
     * 验证密码
     */
    @action
    validatePassword() {
        this.errMsg.password = '';
        if (!this.password) {
            this.errMsg.password = noticeMessage.inputEmpty('密码');
            return false;
        }
        return true;
    }

    @action
    validatePassword1() {
        this.errMsg.password1 = '';
        if (!this.password1) {
            this.errMsg.password1 = noticeMessage.inputEmpty('密码');;
            return false;
        }
        if (!validationUtil.isSimplePassword(this.password1)) {
            this.errMsg.password1 = noticeMessage.passwordFormatError();
            return false;
        }
        return true;
    }

    /**
     * 验证确认密码
     */
    @action
    validateRepeatPassword() {
        this.errMsg.repeatPassword = '';
        if (!this.repeatPassword) {
            this.errMsg.repeatPassword = noticeMessage.inputEmpty('确认密码');
            return false;
        }
        if (this.repeatPassword !== this.password1) {
            this.errMsg.repeatPassword = noticeMessage.repeatPasswordError();
            return false;
        }
        return true;
    }

    /**
     * 验证图形验证码
     */
    @action
    validateCaptcha() {
        this.errMsg.captcha = '';
        if (!this.captcha || !validationUtil.isCaptcha(this.captcha)) {
            this.errMsg.captcha = noticeMessage.inputFormatError('图片验证码');
            return false;
        }
        return true;
    }

    @action
    validateCaptcha1() {
        this.errMsg.captcha1 = '';
        if (!this.captcha1 || !validationUtil.isCaptcha(this.captcha1)) {
            this.errMsg.captcha1 = noticeMessage.inputFormatError('图片验证码');
            return false;
        }
        return true;
    }

    /**
     * 验证短信验证码
     */
    @action
    validateSmsCode() {
        this.errMsg.smsCode = '';
        if (!this.smsCode || !validationUtil.isSMSCode(this.smsCode)) {
            this.errMsg.smsCode = noticeMessage.inputFormatError('短信验证码');
            return false;
        }
        return true;
    }

    /**
     * 发起发送短信验证码请求
     */
    @action
    async sendSmsCode() {
        this.globalErrMsg = '';
        this.isSendSmsCodeSuccess = false;
        if (!this.validateUsername1()) {
            this.closeCaptchaModal();
            return;
        }
        if (!this.validateCaptcha1()) {
            return;
        }
        const res = await this.post('/sms-code', {
            mobile: this.username1,
            captcha: this.captcha1,
            type: 3,
        }, {
                showGlobalLoading: true,
            });
        const code = res.code;
        runInAction(() => {
            if (code === '0000') {
                this.isSendSmsCodeSuccess = true;
                this.smsCodeTimeout = 60;
                this.smsCodeTimer = setInterval(this.updateSmsCodeTimeout.bind(this), 1000);
                this.closeCaptchaModal();
            } else if (code === '1102') {
                this.errMsg.captcha1 = noticeMessage.inputFormatError('图片验证码');
                this.refreshCaptcha1();
            } else if (code === '1201') {
                this.closeCaptchaModal();
                this.globalErrMsg = noticeMessage.requestSmsCodeTooFast();;
            } else if (code === '1202') {
                this.closeCaptchaModal();
                this.globalErrMsg = '无法继续获取验证码,请稍后找回密码';
            } else if (code === '1204') {
                this.closeCaptchaModal();
                this.errMsg.username1 = '用户不存在，请重试';
            } else {
                this.closeCaptchaModal();
                this.globalErrMsg = res.message || '获取短信验证码失败，请重试';
            }
        });
    }

    @action
    updateSmsCodeTimeout() {
        runInAction(() => {
            if (this.smsCodeTimeout > 0) {
                this.smsCodeTimeout--;
                return;
            }
            clearInterval(this.smsCodeTimer);
        });
    }

    @action
    async login() {
        this.globalErrMsg = '';
        if (!this.validateUsername() || !this.validatePassword() || !this.validateCaptcha()) {
            return;
        }
        const res = await this.post('/user/signin', {
            username: this.username,
            password: this.password,
            captcha: this.captcha,
        }, {
                showGlobalLoading: true,
            });
        const code = res.code;
        runInAction(() => {
            if (code === '0000') {
                this.isLogon = true;
                Cookies.set('client__user_id', res.data.user_id);
                res.data.enterprise_id && Cookies.set('client__enterprise_id', res.data.enterprise_id);
            } else if (code === '1101') {
                this.errMsg.captcha = noticeMessage.inputFormatError('验证码');
                this.refreshCaptcha();
            } else {
                this.globalErrMsg = res.message || '用户名或密码不正确';
            }
        });
    }

    @action
    async retrievePwd() {
        this.globalErrMsg = '';
        if (!this.validateUsername1() || !this.validateSmsCode() || !this.validatePassword1() || !this.validateRepeatPassword()) {
            return;
        }
        const res = await this.post('/user/reset-password', {
            username: this.username1,
            password: this.password1,
            repeat_password: this.repeatPassword,
            mobile_verify_code: this.smsCode
        }, {
                showGlobalLoading: true,
            });
        const code = res.code;
        runInAction(() => {
            if (code === '0000') {
                this.isRetrievePwdSuccess = true;
                this.closeRetrievePwdModal();
            } else if (code === '1201') {
                this.errMsg.smsCode = noticeMessage.smsCodeError();
            } else if (code === '1202') {
                this.errMsg.smsCode = noticeMessage.smsCodeExpire();
            } else if (code === '1203') {
                this.errMsg.username1 = '用户不存在，请重试';
            } else {
                this.globalErrMsg = res.message || '重置密码失败，请重试';
            }
        });
    }
}

export default new LoginStore();
